import Taro from "@tarojs/taro";
import ApiWork from "@/api/work";
import useFetch from "@/hooks/useFetch";
import useForm from "@/hooks/useForm";
import { ConstructionPlanForm } from "@/types/work";

export default (routerParams) => {
  const { loading: loading2, runAsync } = useFetch(
    ApiWork.submitConstructionPlan,
    "POST",
    {
      manual: true,
      onSuccess() {
        Taro.showToast({ title: "保存成功！" });
        setTimeout(() => {
          Taro.redirectTo({
            url: `/packageWork/pages/plan/detail?intentCustomerId=${routerParams.intentCustomerId}`,
          });
        }, 1500);
      },
    }
  );

  // 提交表单
  const { loading, model, setModel, submitAsync } =
    useForm<ConstructionPlanForm>(ApiWork.createConstructionPlan, {
      defaultModel: {
        // 是否跳过节假日
        isSkipHoliday: true,
        // 计划开工时间
        planStartDate: "",
        formConstructionPlanList: [],
      }
    });

  /**
   * 提交（正式提交）
   * @param newModel
   */
  const submit = async (newModel?: Record<string, any>) => {
    // {constructionId:number}
    const res = await submitAsync(newModel);
    runAsync(res);
  };

  /**
   * 保存为草稿
   * @param newModel
   */
  const submitAsDraft = (newModel?: Record<string, any>) => {
    return new Promise(async (resolve) => {
      const res = await submitAsync(newModel);
      Taro.showToast({ title: "保存草稿成功" })
      setTimeout(() => {
        resolve(res)
      }, 1500)
    })
  }


  return {
    loading: loading || loading2,

    model,
    setModel,
    submit,
    submitAsDraft,
  };
};
